using Microsoft.EntityFrameworkCore;
using MESData.ErrorCode;
using MESData.Infrastucture;
using BOMAPI.DTO;
using MESBaseis.Domain.BOM;

namespace BOMAPI.Services
{
    public interface IManagementService
    {
        Task<ApiPageing<ManagementResultDto>> GetManagementAsync(ManagementQueryDto queryDto);
        Task<ApiResult<ManagementResultDto>> CreateManagementAsync(ManagementCreateDto createDto);
    }

    public class ManagementService : IManagementService
    {
        private readonly MyDbcontext _context;

        public ManagementService(MyDbcontext context)
        {
            _context = context;
        }

        public async Task<ApiPageing<ManagementResultDto>> GetManagementAsync(ManagementQueryDto queryDto)
        {
            try
            {
                var query = _context.Management
                    .Where(m => !m.IsDeleted)
                    .AsQueryable();

                if (!string.IsNullOrWhiteSpace(queryDto.Keyword))
                {
                    var k = queryDto.Keyword;
                    query = query.Where(m =>
                        m.BOMId.Contains(k) ||
                        m.BOMTheme.Contains(k) ||
                        m.ProductNumber.Contains(k) ||
                        m.ProductName.Contains(k) ||
                        m.Specification.Contains(k));
                }

                if (!string.IsNullOrWhiteSpace(queryDto.Brand))
                {
                    query = query.Where(m => m.Brand.Contains(queryDto.Brand));
                }

                var totalCount = await query.CountAsync();

                var list = await query
                    .OrderByDescending(m => m.Id)
                    .Skip((queryDto.PageIndex - 1) * queryDto.PageSize)
                    .Take(queryDto.PageSize)
                    .Select(m => new ManagementResultDto
                    {
                        Id = m.Id,
                        BOMId = m.BOMId,
                        BOMTheme = m.BOMTheme,
                        ProductNumber = m.ProductNumber,
                        ProductName = m.ProductName,
                        Specification = m.Specification,
                        ProductId = m.ProductId,
                        unit = m.unit,
                        Brand = m.Brand,
                        DefaultBOM = m.DefaultBOM,
                        DailyOutput = m.DailyOutput
                    })
                    .ToListAsync();

                var totalPage = (int)Math.Ceiling((double)totalCount / queryDto.PageSize);

                return new ApiPageing<ManagementResultDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    TotaCount = totalCount,
                    TotaPage = totalPage,
                    PageData = list
                };
            }
            catch (Exception ex)
            {
                return new ApiPageing<ManagementResultDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"查询失败：{ex.Message}",
                    Data = null,
                    TotaCount = 0,
                    TotaPage = 0,
                    PageData = null
                };
            }
        }

        public async Task<ApiResult<ManagementResultDto>> CreateManagementAsync(ManagementCreateDto createDto)
        {
            try
            {
                // 检查BOM编号是否已存在
                var existingBOM = await _context.Management
                    .Where(m => m.BOMId == createDto.BOMId && !m.IsDeleted)
                    .FirstOrDefaultAsync();

                if (existingBOM != null)
                {
                    return new ApiResult<ManagementResultDto>
                    {
                        Code = ApiEnum.Error,
                        Msg = "BOM编号已存在，请使用不同的编号"
                    };
                }

                // 创建新的ManagementModel
                var newManagement = new ManagementModel
                {
                    BOMId = createDto.BOMId,
                    BOMTheme = createDto.BOMTheme,
                    ProductNumber = createDto.ProductNumber,
                    ProductName = createDto.ProductName,
                    Specification = createDto.Specification ?? "",
                    ProductId = createDto.ProductId ?? "",
                    unit = createDto.unit ?? "",
                    Brand = createDto.Brand ?? "",
                    DefaultBOM = createDto.DefaultBOM ?? "N",
                    DailyOutput = createDto.DailyOutput ?? "",
                    ItemIds = createDto.ItemIds ?? "",
                    ProcessFlowIds = createDto.ProcessFlowIds ?? "",
                    IsDeleted = false
                };

                _context.Management.Add(newManagement);
                await _context.SaveChangesAsync();

                // 返回创建成功的结果
                var resultDto = new ManagementResultDto
                {
                    Id = newManagement.Id,
                    BOMId = newManagement.BOMId,
                    BOMTheme = newManagement.BOMTheme,
                    ProductNumber = newManagement.ProductNumber,
                    ProductName = newManagement.ProductName,
                    Specification = newManagement.Specification,
                    ProductId = newManagement.ProductId,
                    unit = newManagement.unit,
                    Brand = newManagement.Brand,
                    DefaultBOM = newManagement.DefaultBOM,
                    DailyOutput = newManagement.DailyOutput,
                    ItemIds = newManagement.ItemIds,
                    ProcessFlowIds = newManagement.ProcessFlowIds
                };

                return new ApiResult<ManagementResultDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "创建成功",
                    Data = resultDto
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<ManagementResultDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"创建失败：{ex.Message}"
                };
            }
        }
    }
}


